package okhttp3.brotli.internal;

import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpHeaders;
import okio.BufferedSource;
import okio.GzipSource;
import okio.Okio;
import okio.Source;
import org.brotli.dec.BrotliInputStream;

import java.io.IOException;
import java.io.InputStream;

public class BrotliKt {
    public static final Response uncompress( Response response) {
        if (!HttpHeaders.hasBody(response)) {
            return response;
        } else {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                ResponseBody body = responseBody;
                String string=response.header("Content-Encoding");
                if (string != null) {
                    String encoding = string;
                    BufferedSource bufferedSource = null;
                    if (encoding.equals("br")) {
                        try {
                            bufferedSource = Okio.buffer(Okio.source((InputStream)(new BrotliInputStream(body.source().inputStream()))));
                        } catch (IOException e) {
                            e.fillInStackTrace();
                        }
                    } else {
                        if (!encoding.equals("gzip")) {
                            return response;
                        }

                        bufferedSource = Okio.buffer((Source)(new GzipSource((Source)body.source())));
                    }

                    BufferedSource decompressedSource = bufferedSource;
                    return response.newBuilder().removeHeader("Content-Encoding").removeHeader("Content-Length").body(ResponseBody.create( body.contentType(), -1L,decompressedSource)).build();
                } else {
                    return response;
                }
            } else {
                return response;
            }
        }
    }
}
